package com.ice.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.reflection.wrapper.ObjectWrapper;
import org.ice.entity.ReceiveXmlEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ice.common.GenerateEntity;
import com.ice.common.IceConstants;
import com.ice.common.IceLog;
import com.ice.common.IceProperties;
import com.ice.common.SHA1;

import com.ice.service.WeChatService;
import com.ice.tools.ReceiveWechatByHttp;



@Service("WinXinService")
public class WeChatServiceImpl implements WeChatService{
	
    Logger log =LoggerFactory.getLogger(WeChatServiceImpl.class);
	
    @Override
	public boolean checkSignature(ArrayList<String> parameters,String signature) {
		// TODO Auto-generated method stub
		/* 连接微信，给腾讯服务器返回信息
		 * 加密/校验流程如下：
	     * 1. 将token、timestamp、nonce三个参数进行字典序排序
	     * 2. 将三个参数字符串拼接成一个字符串进行sha1加密
	     * 3. 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
	     */
    	long startTime = System.currentTimeMillis();
    	
		Collections.sort(parameters);//1. 将token、timestamp、nonce三个参数进行字典序排序
		
		StringBuilder sb = new StringBuilder();
		for(int i=0; i<parameters.size();i++){
			sb.append(parameters.get(i));
		}
		
		String shaStr = SHA1.SHA1(sb.toString());//将三个参数字符串拼接成一个字符串进行sha1加密
		
	
		if(shaStr.equals(signature)){// 开发者获得加密后的字符串可与signature对比
			log.debug("{}",IceLog.printLog(startTime, "获得加密后的字符串可与signature对比", "signature校验正确"));
			return true;
		
		}

	    log.debug("{}",IceLog.printLog(startTime, "获得加密后的字符串可与signature对比", "signature校验失败"));
	   return false;

	}
    
    /**
     * 获得授权access_token
     */
	@Override
	public String getAccessToken() {
		long startTime = System.currentTimeMillis();
		
		String appid = IceProperties.getValue(IceConstants.WECHAT_PROPERTIES_URI, IceConstants.WECHAT_APP_ID);
		String appsecret = IceProperties.getValue(IceConstants.WECHAT_PROPERTIES_URI, IceConstants.WECHAT_APPSECRET);
		String apiurl = IceConstants.WECHAT_ACCESS_TOKEN_URL;
		
		//拼接accessTokenUrl
		String accessTokenUrl=String.format(apiurl, appid, appsecret);
		log.debug("{}",IceLog.printLog(startTime, "获取access token 操作", "access token 的请求url为："+accessTokenUrl));

		String access_token = null;
		
		Map<Object, Object> map = ReceiveWechatByHttp.receive(accessTokenUrl);
		if(map.get("errcode")!=null){// 错误时微信会返回错误码等信息，{"errcode":40013,"errmsg":"invalid appid"}	
			log.debug("{}",IceLog.printLog(startTime, "获取access token 操作", "错误信息："+"{'errcode':40013,'errmsg':'invalid appid'}"));
			return null;
		}else{
    	  access_token =(String)map.get("access_token");
    	}
		
		log.debug("{}",IceLog.printLog(startTime, "获取access token 操作", "access token为："+access_token));
		return access_token;
	}

	@Override
	public ReceiveXmlEntity processWeChatMessage(String xml) {
		// TODO Auto-generated method stub
		ReceiveXmlEntity entity =(ReceiveXmlEntity) GenerateEntity.byXml(xml, "org.ice.entity.ReceiveXmlEntity", new ReceiveXmlEntity());
		
		return entity;
	}
	/**
	 * 通过code换取网页授权nopenid
	 */
	@Override
	public String getOpenId(String code) {
		//获取code后，请求以下链接获取access_token： 
		//https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
        long startTime = System.currentTimeMillis();
		
		String appid = IceProperties.getValue(IceConstants.WECHAT_PROPERTIES_URI, IceConstants.WECHAT_APP_ID);
		String appsecret = IceProperties.getValue(IceConstants.WECHAT_PROPERTIES_URI, IceConstants.WECHAT_APPSECRET);
		String apiurl = IceConstants.WECHAT_ACCESS_TOKEN_WEB_AUTHOR_URL;
		
		//拼接accessTokenUrl
		String accessTokenUrl=String.format(apiurl, appid, appsecret,code);
		log.debug("{}",IceLog.printLog(startTime, "通过code获取openid", "通过code获取openid的请求url为："+accessTokenUrl));

		String openid = null;
		
		Map<Object, Object> map = ReceiveWechatByHttp.receive(accessTokenUrl);
		if(map.get("errcode")!=null){
			//错误时微信会返回JSON数据包如下（示例为Code无效错误）:
            //{"errcode":40029,"errmsg":"invalid code"}
			log.debug("{}",IceLog.printLog(startTime, "通过code获取openid", "错误信息："+"{'errcode':40029,'errmsg':'invalid code'}"));
			return null;
		}else{
			openid =(String)map.get("openid");
    	}
		
		log.debug("{}",IceLog.printLog(startTime, "通过code获取openid", "openid为："+openid));
		return openid;
	}
	
	/**
	 * 通过code换取网页授权access_token
	 */
	@Override
	public String getWebAuthorAccessToken(String code) {
		//获取code后，请求以下链接获取access_token： 
				//https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
		        long startTime = System.currentTimeMillis();
				
				String appid = IceProperties.getValue(IceConstants.WECHAT_PROPERTIES_URI, IceConstants.WECHAT_APP_ID);
				String appsecret = IceProperties.getValue(IceConstants.WECHAT_PROPERTIES_URI, IceConstants.WECHAT_APPSECRET);
				String apiurl = IceConstants.WECHAT_ACCESS_TOKEN_WEB_AUTHOR_URL;
				
				//拼接accessTokenUrl
				String accessTokenUrl=String.format(apiurl, appid, appsecret,code);
				log.debug("{}",IceLog.printLog(startTime, "通过code换取网页授权access_token", "通过code获取access_token的请求url为："+accessTokenUrl));

				String accessToken = null;
				
				Map<Object, Object> map = ReceiveWechatByHttp.receive(accessTokenUrl);
				if(map.get("errcode")!=null){
					//错误时微信会返回JSON数据包如下（示例为Code无效错误）:
		            //{"errcode":40029,"errmsg":"invalid code"}
					log.debug("{}",IceLog.printLog(startTime, "通过code换取网页授权access_token", "错误信息："+"{'errcode':40029,'errmsg':'invalid code'}"));
					return null;
				}else{
					accessToken =(String)map.get("openid");
		    	}
				
				log.debug("{}",IceLog.printLog(startTime, "通过code换取网页授权access_token", "access_token为："+accessToken));
				return accessToken;
	}
	
	/**
	 * http：GET（请使用https协议）
	 * https://api.weixin.qq.com/sns/auth?access_token=ACCESS_TOKEN&openid=OPENID
	 * 正确的Json返回结果：
	 * { "errcode":0,"errmsg":"ok"}
	 * 错误时的Json返回示例：
	 * { "errcode":40003,"errmsg":"invalid openid"}
	 * 
	 */
	@Override
	public boolean checkWebAuthorAccessToken(String accessToken,String openid) {
		// TODO Auto-generated method stub
		 long startTime = System.currentTimeMillis();

		String apiurlFormat = IceConstants.WECHAT_CHECK_WEB_ACCESS_TOKEN;
		//System.out.println(apiurlFormat);
		String accessTOKENURL = String.format(apiurlFormat,accessToken,openid);
		
		
		Map<String, String> map = ReceiveWechatByHttp.receive(accessTOKENURL);
		String returnMsg = map.get("errcode");
		//System.out.println(returnMsg);
		if("40003".equals(returnMsg)){
			log.debug("{}",IceLog.printLog(startTime, "检查网页授权access_token是否失效", "access_token已经失效，需要重新获取access_token"));
			return false;
		}else if("0".equals(returnMsg)){
			log.debug("{}",IceLog.printLog(startTime, "检查网页授权access_token是否失效", "access_token未失效"));
			return true;
			
		}else{
			log.debug("{}",IceLog.printLog(startTime, "检查网页授权access_token是否失效", "异常，建议重新获取access_token"));
			return false;
			
		}
		
	}
	
	
	
}
